import os
import sys
import psycopg2
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class ProjectList(QListWidget):
    project_data_Signal=pyqtSignal(dict)
    def __init__(self):
        super(ProjectList, self).__init__()

        self.doubleClicked.connect(self.choose_project)


    def create_items(self,data_list):
        if data_list:
            self.clear()
            for i in data_list:
                full_name=i['full_name']
                entity_name=i['entity_name']
                project_name=full_name+'('+entity_name+')'
                color=i['color']
                item=QListWidgetItem()
                item.setData(5,i)
                item.setText(project_name)
                item.setTextAlignment(Qt.AlignCenter)
                item.setBackground(QBrush(QColor(color)))
                self.addItem(item)
            self.sortItems()

    def choose_project(self,index):
        select_item=self.itemFromIndex(index)
        data=select_item.data(5)
        print('choose_project:',data)
        self.project_data_Signal.emit(data)


    def filter_item(self,text):
        try:
            item_list=[]
            for i in range(self.count()):
                item=self.item(i)
                project_name=item.text()
                if text not in project_name:
                    # item_list.append(item)
                    item.setHidden(True)
                    # item=QListWidgetItem()
                    # item.setHidden()
            # for g in item_list:
            #     self.addItem(g)
            # self.sortItems()
        except Exception as filter_item_ERR:
            print(str(filter_item_ERR))

    def show_all(self):
        for i in range(self.count()):
            item = self.item(i)
            item.setHidden(False)



class ProjectWindow(QWidget):
    database_Signal=pyqtSignal(dict)
    def __init__(self,icon,IMG_PATH):
        super(ProjectWindow, self).__init__()
        self.CONFIG_PATH=os.path.join(os.path.dirname(__file__),'config')
        self.project_config_path=os.path.join(self.CONFIG_PATH,'project_config')
        self.pipeline_config_path=os.path.join(self.CONFIG_PATH,'pipeline_config')
        self.db_config_path=os.path.join(self.CONFIG_PATH,'db_config')

        self.data_list=[]  #查询到的所有项目信息列表
        self.icon=icon
        self.IMG_PATH=IMG_PATH
        self.setWindowIcon(self.icon)
        self.setWindowTitle('选择项目,双击选择')
        self.main_layout=QVBoxLayout()
        self.show_label=QLabel('项目列表')
        self.search_layout=QHBoxLayout()
        self.search_edit=QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn=QPushButton('搜索')
        # self.search_btn.setShortcut(Qt.Key_Return|Qt.Key_Enter)
        self.search_btn.setShortcut(Qt.Key_Return)
        # self.search_btn.setShortcut(Qt.Key_Enter)
        self.search_btn.clicked.connect(self._search)
        seach_icon=QIcon()
        seach_icon.addPixmap(QPixmap(os.path.join(self.IMG_PATH,'ss.png')))
        self.search_btn.setIcon(seach_icon)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.project_list=ProjectList()
        self.project_list.project_data_Signal.connect(self._get_project_data)
        self.init_project_list()
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addWidget(self.project_list)

        self.setLayout(self.main_layout)

    def init_project_list(self):
        db = {}
        try:
            with open(self.db_config_path, 'r', encoding='utf8') as r:
                db = eval(r.read())
            if db:
                # print(db)
                time_connect = psycopg2.connect(database=db['db'], user=db['user'], password=db['password'],
                                                host=db['ip'], port=db['port'])
                time_cursor = time_connect.cursor()
                select_sql = "select database,entity_name,full_name,color,frame_rate from timeaxis.r_project where status not in ('Close')"
                try:
                    time_cursor.execute(select_sql)
                    result=time_cursor.fetchall()
                    data_list=[]
                    if result:
                        for i in result:
                            data={}
                            data['database']=i[0]
                            data['entity_name']=i[1]
                            data['full_name']=i[2]
                            data['color']=i[3]
                            data['frame_rate']=i[4]
                            data_list.append(data)
                    if data_list:
                        self.create_items(data_list)
                        self.data_list=data_list

                except Exception as sql_ERR:
                    print('sql_ERR:',str(sql_ERR))
                finally:
                    time_connect.close()
        except Exception as init_project_list_ERR:
            print(str(init_project_list_ERR))

    def create_items(self,data_list):
        if data_list:
            self.project_list.create_items(data_list)

    def _text_edited(self,ha):
        if not ha:  #当没有搜索内容时，就重置
            # self.create_items(self.data_list)
            self.project_list.show_all()

    def _search(self):
        """
        搜索内容
        :return:
        """
        text=self.search_edit.text()
        if text:
            self.project_list.filter_item(text)

    def _get_project_data(self,data):
        """
        获取到选择的项目，之后开始配置该项目的数据
        :param data:
        :return:
        """
        self.database_Signal.emit(data)
        print(data)
        self.close()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    p=ProjectWindow()
    p.show()
    sys.exit(app.exec_())